﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

namespace UplopadQCloudDemo
{
    public static class Common
    {
        public static string ToSHA1(this string filePath)
        {
            var strResult = "";
            var strHashData = "";
            byte[] arrbytHashValue;
            FileStream oFileStream = null;
            SHA1CryptoServiceProvider osha1 = new SHA1CryptoServiceProvider();
            try
            {
                oFileStream = new FileStream(filePath.Replace("\"", ""), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                arrbytHashValue = osha1.ComputeHash(oFileStream); 
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return strResult;
        }

        public static T JsonStringToObj<T>(this string json) where T : class
        {
            return JsonStringToObj<T>(json, null);
        }

        public static T JsonStringToObj<T>(this string json, JsonSerializerSettings settings) where T : class
        {
            try
            {
                if (string.IsNullOrEmpty(json))
                    return null;
                if (settings == null)
                    return JsonConvert.DeserializeObject<T>(json);
                else
                    return JsonConvert.DeserializeObject<T>(json, settings);
            }
            catch (Exception ex)
            {
                throw new Exception("ToJsonString" + json + ex.Message);
            }
        }

        public static object JsonStringToObj(this string json, Type type)
        {
            try
            {
                if (string.IsNullOrEmpty(json))
                    return null;

                return JsonConvert.DeserializeObject(json, type);
            }
            catch (Exception ex)
            {
                throw new Exception("ToJsonString" + json + ex.Message);
            }
        }
    }
}